/**
 * Created by zhuhuijun on 2017-7-26 16:29:44
 * http拦截器处理
 */
angular.module('app.libs').factory('httpInterceptor', ['$log', '$q', '$injector', '$rootScope', 'toaster',
    function ($log, $q, $injector, $rootScope, toaster) {
        var interceptors = {
            request: function (config) {
                var deferred = $q.defer();
                if (_.endsWith(config.url, ".do")) {
                    $rootScope.loading = $rootScope.loading ? $rootScope.loading + 1 : 1;
                    $rootScope.loadingLayerIndex = layer.load(1,
                        {
                            shade: [0.1, '#fff'] //0.1透明度的白色背景
                        });
                }

                deferred.resolve(config);
                return deferred.promise;
            },
            requestError: function (config) {
                return config;
            },
            response: function (response) {
                var deferred = $q.defer();
                if (response.status == 200) {
                    if (response.data.errorMsg) {
                        $rootScope.loading--;
                        layer.close($rootScope.loadingLayerIndex);
                        toaster.pop('error', '错误信息', response.data.errorMsg);
                        deferred.reject(response);
                        return deferred.promise;
                    } else if (_.endsWith(response.config.url, ".do") || response.config.url.indexOf(".do") >= 0) {
                        $rootScope.loading--;
                        if ($rootScope.loading == 0) {
                            layer.close($rootScope.loadingLayerIndex);
                        }
                        deferred.resolve(response);
                        return deferred.promise;
                    }
                    deferred.resolve(response);
                    return deferred.promise;
                }
                if(response.status==203){
                    if(response.data.code=="90001") {
                        window.location.href = "login.html";
                    }
                }
            },
            responseError: function (rejection) {
                $rootScope.loading--;
                if ($rootScope.loading == 0) {
                    layer.close($rootScope.loadingLayerIndex);
                }
                $rootScope.$broadcast({
                    401: "page:notAuthorized", //未授权的请求
                    404: "page:notFound",  //返回404则广播pageNotfound事件
                    500: "server:error"//返回500则广播serverErroe事件
                }[rejection.status]);
                return $q.reject(rejection);
            }
        }
        return interceptors;
    }])
;